#include <jni.h>
#include <string>
#include "libyuv/scale.h"
#include "libyuv/scale_argb.h"
#include "ALog.h"
#include <jni.h>


libyuv::FilterMode getFilterMode(int modeNum) {
    libyuv::FilterMode mode = libyuv::kFilterNone;
    switch (modeNum) {
        case 0:
            mode = libyuv::kFilterNone;
            break;
        case 1:
            mode = libyuv::kFilterLinear;
            break;
        case 2:
            mode = libyuv::kFilterBilinear;
            break;
        case 3:
            mode = libyuv::kFilterBox;
            break;
    }
    return mode;
}

extern "C" jint
Java_com_junmeng_libyuv_jni_ScaleUtil_i420Scale(JNIEnv *env, jobject thiz, jbyteArray src,
                                                jint src_width, jint src_height, jbyteArray dst,
                                                jint dst_width, jint dst_height, jint mode) {
    uint8_t *_src = reinterpret_cast<uint8_t *>(env->GetByteArrayElements(src, nullptr));
    uint8_t *_dst = reinterpret_cast<uint8_t *>(env->GetByteArrayElements(dst, nullptr));


    int ret = libyuv::I420Scale(
            _src,
            src_width,
            _src + src_width * src_height,
            src_width / 2,
            _src + src_width * src_height * 5 / 4,
            src_width / 2,
            src_width,
            src_height,
            _dst,
            dst_width,
            _dst + dst_width * dst_height,
            dst_width / 2,
            _dst + dst_width * dst_height * 5 / 4,
            dst_width / 2,
            dst_width,
            dst_height,
            getFilterMode(mode));
    if (ret == 0) {
        LOGI("I420Scale success");
    } else {
        LOGE("I420Scale fialed:%d", ret);
    }
    env->ReleaseByteArrayElements(src, reinterpret_cast<jbyte *>(_src), JNI_ABORT);
    env->ReleaseByteArrayElements(dst, reinterpret_cast<jbyte *>(_dst), JNI_ABORT);
    return ret;
}

extern "C" jint
Java_com_junmeng_libyuv_jni_ScaleUtil_argbScale(JNIEnv *env, jobject thiz, jbyteArray src,
                                                jint src_width, jint src_height, jbyteArray dst,
                                                jint dst_width, jint dst_height, jint mode) {
    uint8_t *_src = reinterpret_cast<uint8_t *>(env->GetByteArrayElements(src, nullptr));
    uint8_t *_dst = reinterpret_cast<uint8_t *>(env->GetByteArrayElements(dst, nullptr));

    int ret = libyuv::ARGBScale(
            _src,
            src_width * 4,
            src_width,
            src_height,
            _dst,
            dst_width * 4,
            dst_width,
            dst_height,
            getFilterMode(mode));
    if (ret == 0) {
        LOGI("ARGBScale success");
    } else {
        LOGE("ARGBScale fialed:%d", ret);
    }
    env->ReleaseByteArrayElements(src, reinterpret_cast<jbyte *>(_src), JNI_ABORT);
    env->ReleaseByteArrayElements(dst, reinterpret_cast<jbyte *>(_dst), JNI_ABORT);
    return ret;
}